package cn.lotusnut.rabbitmqboot.kill;

import cn.lotusnut.rabbitmqboot.util.RedisUtil;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author JiangMing Zhou
 * @Date 2022/12/1 16:20
 * @Version 1.8
 */
@Slf4j
@Component
public class KillConsumer {

    @Resource
    private RedisUtil redisUtil;


    /**
     * 消费消息
     *
     * @param message
     */
    @RabbitListener(queues = "kill_queue")
    public void consumer(Channel channel, Message message) throws IOException {
        log.debug("秒杀消费者：" + new String(message.getBody(), StandardCharsets.UTF_8));
        Integer stock = (Integer) redisUtil.get("stock");
        if (stock > 0){
            stock--;
            log.debug("秒杀成功：当前库存还剩："+stock);
            redisUtil.set("stock",stock);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }else {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
        }
    }
}
